package com.xx.robot.thrid;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xx.robot.common.util.mongo.MongoDbUtil;
import com.xx.robot.config.ThreadConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.SampleOperation;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * @author Administrator
 */
@Slf4j
@Component
public class PigImageUtil {

    @Autowired
    private ThreadConfig threadConfig;

    /**
     * 老婆图
     */
    public void init() {

        ThreadPoolTaskExecutor ex = this.threadConfig.taskBillExecutor();
        //保证所有线程执行完成
        CountDownLatch latch = new CountDownLatch(1);

        //多线程获取数据并且筛选
        ex.execute(() -> {
            try {
                List<JSONObject> mapsList = MongoDbUtil.selectAll(JSONObject.class, "pigjpg_com");
                if (CollUtil.isNotEmpty(mapsList)) {
                    return;
                }
                int page = 0;
                while (true) {
                    page++;
                    HashMap<String, Object> paramMap = new HashMap<>(8);
                    paramMap.put("order", "-create_time");
                    paramMap.put("page", page + "");
                    String result = HttpUtil.get("https://pigjpg.com/api/pic/", paramMap);
                    if (!JSONUtil.isJson(result)) {
                        log.error("获取失败");
                        return;
                    }
                    JSONArray picList = JSONUtil.parseObj(result).getJSONArray("pics");
                    //死循环退出条件
                    if (CollUtil.isEmpty(picList)) {
                        return;
                    }

                    //每页得业务代码
                    ArrayList<Map<String, Object>> maps = new ArrayList<>();
                    for (Object pic : picList) {
                        JSONObject data = (JSONObject) pic;
                        JSONArray srcList = data.getJSONObject("info").getJSONArray("src");
                        if (CollUtil.isNotEmpty(srcList)) {

                            JSONArray herfList = srcList.getJSONArray(0);
                            if (CollUtil.isNotEmpty(herfList)) {
                                String url = herfList.getStr(0);
                                if (url.startsWith("https://")) {
                                    Map<String, Object> objectObjectHashMap = new HashMap<>(4);
                                    objectObjectHashMap.put("url", url);
                                    maps.add(objectObjectHashMap);
                                }
                            }
                        }
                    }
                    MongoDbUtil.insertMulti(maps, "pigjpg_com");
                    //限制访问频率，以免被封ip
                    Thread.sleep(3000);
                }
            } catch (Exception e) {
                log.error("更新失败");
            } finally {
                latch.countDown();
            }
        });
    }

    /**
     * 获取随机图片
     *
     * @return 获取随机图片
     */
    public String pigImage() {
        SampleOperation sample = Aggregation.sample(1);
        Aggregation aggregation = Aggregation.newAggregation(sample);
        AggregationResults<JSONObject> image = MongoDbUtil.aggregate(aggregation, "pigjpg_com", JSONObject.class);
        JSONObject uniqueMappedResult = image.getUniqueMappedResult();
        if (ObjectUtil.isNotNull(uniqueMappedResult)) {
            String url = uniqueMappedResult.getStr("url");
            return "[CQ:image,file=" + url + ",url=" + url + "]";
        }
        return "";
    }

}
